<template>
  <div class="my_container" style="height: calc(100% - 53px)">
    <div style="height: calc(100% - 48px); overflow: scroll">
      <van-cell-group>
        <van-cell title="工程单号" :value="stock?.OrderCode" />
        <van-cell title="生产单号" :value="stock?.QrCode" />
        <van-cell title="部件号" :value="stock?.ProductName" />
        <van-cell title="库位号" clickable :value="stock?.PlaceCode" />
        <van-cell title="入库数" :value="stock?.Qty" />
        <van-cell title="现存数" :value="stock?.OnHand" />
        <van-cell title="历史出库" clickable is-link @click="to_history" />
        <van-field name="stepper" label="本期出库">
          <template #input>
            <van-stepper v-model="stockOutQty" :min="0" :max="stock?.OnHand" />
          </template>
        </van-field>
        <van-field name="del_btn">
          <template #right-icon>
            <van-button icon="delete-o" type="danger" @click="doStockDel"></van-button>
          </template>
        </van-field>
      </van-cell-group>
    </div>
    <van-button type="primary" @click="doStockOut" size="large">确认出库</van-button>

    <van-overlay :show="loading">
      <div class="loading_wrapper"><van-loading type="spinner" size="24" /></div
    ></van-overlay>
  </div>
</template>
<script setup lang="ts">
import { getStock, stockOut, removeStockOut } from '@/api/stock';
import type { StockModel } from '@/model/stockmodel';
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { error, success } from '@/utils/navigatorUtil';

const stockOutQty = ref(0);
const loading = ref(false);
const stock = ref<StockModel>();
const router = useRouter();
const pk = ref('');
const doStockDel = () => {
  showConfirmDialog({
    title: '提示',
    message: '您确实要删除这笔记录吗？',
  }).then(() => {
    loading.value = true;
    removeStockOut(pk.value)
      .then((r) => {
        showFailToast('操作成功');
        success();
        router.back();
      })
      .catch((e) => {
        showFailToast('操作失败');
        error();
        loading.value = false;
      });
  });
};
const doStockOut = () => {
  loading.value = true;
  stockOut({ qty: stockOutQty.value, src: pk.value })
    .then((r) => {
      showSuccessToast('操作成功');
      success();
      onLoad();
    })
    .catch((e) => {
      error();
      loading.value = false;
    });
};
const to_history = () => {
  router.push({ path: '/stockhistory', query: { pk: pk.value } });
};
const onLoad = () => {
  const thisQuery = router.currentRoute.value.query;
  if (!thisQuery || !thisQuery['pk']) return;
  pk.value = thisQuery['pk'].toString();
  loading.value = true;
  getStock(pk.value)
    .then((r) => {
      stock.value = r.Data![0];
      stockOutQty.value = stock.value.OnHand!;
      loading.value = false;
    })
    .catch((e) => {
      loading.value = false;
    });
};
onMounted(onLoad);
</script>

<style scoped></style>
